from django.db.models import Q

from rest_framework import status

from .info import reload_list_in_view

from prj001.permissions import get_queryset_perm


def search_results_view(req_data, sf=None, obj=None, request=None, sz=None, attr_sz=None):

    data = dict()
    queries = []

    try:
        req_data.pop('types')
    except Exception:
        pass

    if not req_data:
        data['msg'] = '无传递参数'
        data['status'] = status.HTTP_400_BAD_REQUEST
        return (data, [])

    for key, value in req_data.items():
        if key == 'types':
            continue

        if not hasattr(obj, key) and not key.startswith('owner'):
            data['msg'] = '传递的字段有误'
            data['status'] = status.HTTP_400_BAD_REQUEST
            return (data, [])
        else:
            orm_lookup = '__'.join((key, 'icontains'))
            queries.append(Q(**{orm_lookup: value}))
    import operator
    from functools import reduce

    if not queries:
        data['msg'] = '无相应数据信息'
        data['status'] = status.HTTP_400_BAD_REQUEST
        return (data, [])

    try:
        # group_info, _ID = get_group_info(sf=sf, obj=obj)
        group_info = get_queryset_perm(sf)
        gen_objects = group_info.filter(reduce(operator.and_, queries))
    except obj.DoesNotExist:
        data['msg'] = '无相应数据信息'
        data['status'] = status.HTTP_400_BAD_REQUEST
        return (data, [])

    data, page, id_list = reload_list_in_view(sf, request,
                                              objs=gen_objects,
                                              serializer_own=sz,
                                              types='info')

    return (data, id_list)
